package com.jsh.erp.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.jsh.erp.filter.TenantSqlFilter;
import com.jsh.erp.utils.Tools;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Objects;

@Configuration
public class TenantConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 1. 添加多租户拦截器
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(
                        RequestContextHolder.getRequestAttributes())).getRequest();
                String token = request.getHeader("X-Access-Token");
                Long tenantId = Tools.getTenantIdByToken(token);
                return tenantId != 0L ? new LongValue(tenantId) : null;
            }

            @Override
            public String getTenantIdColumn() {
                return "tenant_id";
            }

            @Override
            public boolean ignoreTable(String tableName) {
                if (Boolean.parseBoolean(System.getProperty("isInitProject"))){
                    return true;
                }
                HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(
                        RequestContextHolder.getRequestAttributes())).getRequest();
                String token = request.getHeader("X-Access-Token");
                Long tenantId = Tools.getTenantIdByToken(token);

                if (tenantId == 0L) {
                    return true; // 超管忽略所有表
                }

                // 忽略特定表
                return "jsh_sequence".equalsIgnoreCase(tableName)
                        || "jsh_function".equalsIgnoreCase(tableName)
                        || "jsh_user_business".equalsIgnoreCase(tableName) //新增
                        || "jsh_system_config".equalsIgnoreCase(tableName) //新增
                        || "jsh_role".equalsIgnoreCase(tableName)          //新增
                        || "jsh_platform_config".equalsIgnoreCase(tableName)
                        || "jsh_tenant".equalsIgnoreCase(tableName);
            }
        }));

        // 2. 添加分页拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

        return interceptor;
    }

    /**
     * 特定SQL过滤（替代旧的ISqlParserFilter）
     */
    @Bean
    public TenantSqlFilter tenantSqlFilter() {
        return new TenantSqlFilter();
    }

    /**
     * Mapper扫描配置（Spring Boot 3.x更推荐使用@MapperScan注解）
     */
    // 可以删除此方法，改为在启动类上使用@MapperScan
    // @Bean
    // public MapperScannerConfigurer mapperScannerConfigurer() {
    //     MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
    //     scannerConfigurer.setBasePackage("com.jsh.erp.datasource.mappers*");
    //     return scannerConfigurer;
    // }
}